package com.credithc.signature.manager.service;

import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.signature.common.constant.ManagerConstant;
import com.credithc.signature.common.mapper.SealChannelMapper;
import com.credithc.signature.common.mapper.SealInfoMapper;
import com.credithc.signature.common.po.SealChannel;
import com.credithc.signature.common.po.SealInfo;
import com.credithc.signature.common.ro.manager.SealChannelRo;
import com.credithc.signature.common.service.DictionaryService;
import com.credithc.signature.common.vo.manager.SealChannelVo;
import com.credithc.signature.common.vo.manager.SealInfoVo;
import com.credithc.signature.manager.client.AuthClient;
import com.credithc.signature.manager.ro.ProductRo;
import com.credithc.signature.manager.ro.TokenRo;
import com.credithc.signature.manager.vo.CompanyProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SealChannelService {

    @Autowired
    private SealChannelMapper sealChannelMapper;

    @Autowired
    private SealInfoMapper sealInfoMapper;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    CompanyService companyService;

    @Autowired
    AuthClient authClient;


    public PageInfo<SealChannelVo> search(SealChannelRo sealChannelRo) {
        String code = sealChannelRo.getCode();
        Integer companyId = sealChannelRo.getCompanyId();
        Integer userId = sealChannelRo.getUserId();
        CompanyProductVo productMap = companyService.getProductMap(code, companyId, userId);
        Map<String, ProductRo> proMap = productMap.getProMap();
        List<String> channelIds = productMap.getChannelIds();
        if (companyId != null || userId != null) {
            if (channelIds.size() < 1) {
                return new PageInfo<>(new ArrayList<>(), 0, 0, 0);
            } else {
                sealChannelRo.setProductIds(channelIds);
            }
        }
        try {
            List<SealChannelVo> sealChannelVos = sealChannelMapper.queryByRo(sealChannelRo, new RowBounds((sealChannelRo.getPageNo() - 1) * sealChannelRo.getPageSize(), sealChannelRo.getPageSize()));
            int count = sealChannelMapper.queryCountByRo(sealChannelRo);
            for (SealChannelVo sv : sealChannelVos) {
                ProductRo productRo = proMap.get(sv.getChannelId());
                if (productRo != null) {
                    sv.setTenant(productRo.getCompanyName());
                    sv.setSealPerson(productRo.getUserName());
                    sv.setChannelName(productRo.getProductName());
                }
            }

            return new PageInfo<>(sealChannelVos, count, sealChannelRo.getPageNo(), sealChannelRo.getPageSize());
        } catch (Exception e) {
            log.error("类SealChannelService[search]方法发生异常", e);
        }
        return new PageInfo<>(new ArrayList<>(), 0, 0, 0);
    }

    public void updateStatus(Integer id, Integer status) {
        Example example = new Example(SealChannel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        SealChannel sealChannel = new SealChannel();
        sealChannel.setId(id);
        sealChannel.setStatus(status);

        try {
            sealChannelMapper.updateByExampleSelective(sealChannel, example);
        } catch (Exception e) {
        }
    }

    public SealInfoVo getSealInfo(Integer id) {
        Example example = new Example(SealChannel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        SealChannel sealChannel = null;
        try {
            sealChannel = sealChannelMapper.selectOneByExample(example);
        } catch (Exception e) {
        }
        Example ex = new Example(SealInfo.class);
        Example.Criteria criteria1 = ex.createCriteria();
        criteria1.andEqualTo("sealCode", sealChannel.getSealCode());
        SealInfo sealInfo = null;
        try {
            sealInfo = sealInfoMapper.selectOneByExample(ex);
        } catch (Exception e) {
        }
        SealInfoVo sealInfoVo = new SealInfoVo();
        if (sealInfo != null) {
            BeanUtils.copyProperties(sealInfo, sealInfoVo);
        }
        if (StringUtils.isNotEmpty(sealInfo.getIdentificationType())) {
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.CERT_TYPE, sealInfo.getIdentificationType());
            sealInfoVo.setIdentificationTypeName(name);
        }
        return sealInfoVo;
    }

    /**
     * 根据sealCode删除
     *
     * @param sealCode
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void deleteBySealCode(String sealCode) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Message<TokenRo> tokenRo = authClient.getUserInfoByToken(request.getHeader("token"));
            log.info("数据权限查询结果:" + tokenRo.toString());
            if (tokenRo.getData() != null) {
                TokenRo data = tokenRo.getData();
                String productCode = data.getProductCode();
                Example example = new Example(SealChannel.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("sealCode", sealCode);
                criteria.andEqualTo("channelNo",productCode);
                sealChannelMapper.deleteByExample(example);
                log.info("删除SealChannel表信息成功......");
            }
        } catch (Exception e) {
            log.error("删除SealChannel表信息失败......", e);
        }
    }


}
